import { ApiResponse } from '../types';
import {
  getOrders as getOrdersService,
  getOrderById as getOrderByIdService,
  createOrder as createOrderService,
  payOrder as payOrderService,
  cancelOrder as cancelOrderService,
  OrderListQuery,
  OrderListResponse,
  CreateOrderRequest,
  CreateOrderResponse
} from '../service/orderService';

/**
 * Mock API: 获取用户订单列表
 * GET /api/orders
 */
export const GET_orders = async (query: OrderListQuery = {}): Promise<ApiResponse<OrderListResponse>> => {
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 400));

    // 调用Service层
    const result = await getOrdersService(query);

    return result;
  } catch (error) {
    console.error('Get Orders API Error:', error);
    return {
      code: 500,
      message: '网络请求失败',
      data: null
    };
  }
};

/**
 * Mock API: 获取订单详情
 * GET /api/orders/:id
 */
export const GET_order_detail = async (orderId: string): Promise<ApiResponse<{ order: any }>> => {
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));

    // 调用Service层
    const result = await getOrderByIdService(orderId);

    return result;
  } catch (error) {
    console.error('Get Order Detail API Error:', error);
    return {
      code: 500,
      message: '网络请求失败',
      data: null
    };
  }
};

/**
 * Mock API: 创建订单
 * POST /api/orders
 */
export const POST_order = async (body: CreateOrderRequest): Promise<ApiResponse<CreateOrderResponse>> => {
  try {
    // 模拟网络延迟（创建订单稍长一些）
    await new Promise(resolve => setTimeout(resolve, 800));

    // 调用Service层
    const result = await createOrderService(body);

    return result;
  } catch (error) {
    console.error('Create Order API Error:', error);
    return {
      code: 500,
      message: '网络请求失败',
      data: null
    };
  }
};

/**
 * Mock API: 支付订单
 * PUT /api/orders/:id/pay
 */
export const PUT_order_pay = async (orderId: string): Promise<ApiResponse<{ order: any }>> => {
  try {
    // 模拟支付处理时间
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 调用Service层
    const result = await payOrderService(orderId);

    return result;
  } catch (error) {
    console.error('Pay Order API Error:', error);
    return {
      code: 500,
      message: '网络请求失败',
      data: null
    };
  }
};

/**
 * Mock API: 取消订单
 * DELETE /api/orders/:id
 */
export const DELETE_order = async (orderId: string): Promise<ApiResponse<{ order: any }>> => {
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));

    // 调用Service层
    const result = await cancelOrderService(orderId);

    return result;
  } catch (error) {
    console.error('Cancel Order API Error:', error);
    return {
      code: 500,
      message: '网络请求失败',
      data: null
    };
  }
};